import axios from 'axios'
import {useToken, useStore, useConfig, useSaveTokenType, useSessionToken} from '~/store'
const $save_token_type = useSaveTokenType()
let $token;
const post = axios.create({
    method: 'POST'
})
post.interceptors.request.use(config => {
    if ($save_token_type.value === 'local') {
        $token = useToken()
    } else {
        $token = useSessionToken()
    }
    config.headers['Authorization'] = 'Bearer ' + $token.value
    return config
}, error => Promise.reject(error))
post.interceptors.response.use(response => {
    return (response.status === 200) ? response : Promise.reject('[ERROR] response.status: ' + response.status)
}, error => Promise.reject(error))

const $config = useConfig()
export const $post = async (request, loading = false) => {
    const $store = useStore()
    if (loading) $store.api_loading++
    const response = await post(request).catch((e) => {
        window.$message().error($config.value.api.error_message)
    })
    if (loading) $store.api_loading--
    return !!response ? response.data : false
}
